package com.pai4j.oss.controller;

import com.pai4j.common.bean.PAIResponseBean;
import com.pai4j.common.bean.PAIResponseBeanUtil;
import com.pai4j.common.service.MinioService;
import com.pai4j.common.util.DateUtils;
import com.pai4j.domain.vo.response.UploadResultVO;
import com.pai4j.log.annotation.OperationLog;
import com.pai4j.remote.oss.FileServiceClient;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class FileServiceController implements FileServiceClient {

    @Resource
    private MinioService minioService;
    @Resource
    private HttpServletRequest request;

    /**
     * 文件上传
     *
     * @author: CYM-pai
     * @date: 2025/04/27 18:22
     **/
    @OperationLog(
        module = "文件管理",
        operation = "文件上传",
        description = "用户上传文件",
        recordParams = false
    )
    public PAIResponseBean<UploadResultVO> upload(MultipartFile file) {
        String path = request.getHeader("upload-path");
        Assert.isTrue(StringUtils.isNotBlank(path), "上传路径不能为空");
        String timePackage = DateUtils.getDate2String(DateUtils.YYYYMMDD, new Date());
        UploadResultVO uploadResultVO = minioService.upload(path + "/" + timePackage, file, true);
        return PAIResponseBeanUtil.success(uploadResultVO);
    }

    /**
     *  文件编辑
     *
     * @author: CYM-pai
     * @date: 2025/04/27 18:22
     **/
    @OperationLog(
        module = "文件管理",
        operation = "编辑器文件上传",
        description = "用户通过编辑器上传文件",
        recordParams = false
    )
    public PAIResponseBean<UploadResultVO> uploadEditor(@RequestParam("file") MultipartFile file) {
        String path = request.getHeader("upload-path");
        Assert.isTrue(StringUtils.isNotBlank(path), "上传路径不能为空");
        String timePackage = DateUtils.getDate2String(DateUtils.YYYYMMDD, new Date());
        UploadResultVO uploadResultDTO = minioService.upload(path + "/" + timePackage, file, true);
        Map<String, String> urlMap = new HashMap<>();
        urlMap.put("url", uploadResultDTO.getUrl());
        return PAIResponseBeanUtil.success(urlMap);
    }

   /**
    *  下载文件
    *
    * @author: CYM-pai
    * @date: 2025/04/27 18:22
    **/
    @OperationLog(
        module = "文件管理",
        operation = "文件下载",
        description = "用户下载文件",
        recordParams = true
    )
    public void download(@RequestParam String filename, HttpServletResponse response) {
        minioService.download(filename, response);
    }
}
